package com.qf.smsplatfrom.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatfrom.cache.MenuCaChe;
import com.qf.smsplatfrom.constans.ResultCode;
import com.qf.smsplatfrom.dto.R;
import com.qf.smsplatfrom.pojo.TMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ArbitrarilyInterceptor implements HandlerInterceptor {
    private MenuCaChe menuCaChe;

    @Autowired
    public void setMenuCaChe(MenuCaChe menuCaChe) {
        this.menuCaChe = menuCaChe;
    }

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取到当前登录的路径
        String requestURI = request.getRequestURI();
        //这是当前访问路径在map集合中查询到的结果
        TMenu byKey = menuCaChe.getByKey(requestURI);
        //取出状态码判断是否等于1等于1放行，不等于1抛异常
        if (byKey != null) {
            if (byKey.getState() == 0) {
                R error = R.setError(ResultCode.BLOCkL_UP, "十分抱歉，此页面飞到不明太空了，请稍等一下", null);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(objectMapper.writeValueAsString(error));
                return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
